<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<script type="text/javascript">
    require([ "dojo/_base/array", "dojo/_base/xhr", "dojo/request", "dojo/topic", "dojo/json", "dojo/_base/lang",
            "dojo/dom", "dijit/Dialog" ], function(array, xhr, request, topic, JSON, lang, dom, Dialog) {
        var deletItemsCount = 0;
        var refreshTree = "mailfolder/refreshZtree";
        var foldertype = "1";
        mailRestForm = function(formId) {
            dijit.byId(formId).reset();
            dijit.byId("MailNewContent").setValue("");
            dijit.byId("MailUpdateContent").setValue("");
            if (formId.indexOf('UFD') != -1) {
                var rowid = jQuery("#mailGird").jqGrid('getGridParam', 'selrow');
                var mail = jQuery("#mailGird").jqGrid('getRowData', rowid);
                dijit.byId('mailUFD').setValues(mail);
            }
        };
        topic.subscribe("mail/insertOrUpdate", mailRestForm);
        var syncDB = function(url, jsonData) {
            request.post(url, {
                data : jsonData,
                headers : {
                    'Content-Type' : "application/json; charset=utf-8"
                },
                timeout : 30000
            }).then(function(response) {
                topic.publish("notifyMsgTopic", {
                    message : response,
                    type : "message",
                    duration : 1000
                });
                topic.publish(refreshTree);
                var currentPage = jQuery('#mailGird').jqGrid('getGridParam', 'page');
                var pageSize = jQuery('#mailGird').jqGrid('getGridParam', 'rowNum');
                var totalCount = jQuery('#mailGird').jqGrid('getGridParam', 'records') - deletItemsCount;
                var totalPages = Math.ceil(totalCount / pageSize);
                jQuery("#mailGird").jqGrid('setGridParam', {
                    page : currentPage > totalPages ? totalPages : currentPage
                }).trigger("reloadGrid");
            }, function(error) {
                alert(error);
            });
        };
        mailRefresh = function() {
            jQuery("#mailGird").jqGrid('setGridParam', {}).trigger('reloadGrid');
        };
        mailSubmitForm = function(formId, type) {
            var url = "mail/insert";
            if (type == 'u') {
                url = "mail/update";
            }
            var form = dijit.byId(formId);
            if (form.isValid()) {
                var formData = form.getValues();
                var mailstatustemp = "1";

                var fileIds = dom.byId("uploadFilesI").value;
                lang.mixin(formData, {
                    senderid : userid,
                    sender : username,
                    userid : userid,
                    mailstatus : mailstatustemp,
                    filenames : fileIds
                });
                var json = JSON.stringify(formData);
                syncDB(url, json);
                form.hide();
                topic.publish("mail/insertOrUpdate", formId);
            } else {
                form.validate();
            }
        };
        mailSaveSubmitForm = function(formId, type) {
            var url = "mail/insert";
            var form = dijit.byId(formId);
            if (form.isValid()) {
                var formData = form.getValues();
                var mailstatustemp = "0";
                var fileIds = dom.byId("uploadFilesI").value;
                lang.mixin(formData, {
                    senderid : userid,
                    sender : username,
                    mailstatus : mailstatustemp,
                    filenames : fileIds
                });
                var json = JSON.stringify(formData);
                syncDB(url, json);
                form.hide();
                topic.publish("mail/insertOrUpdate", formId);
            } else {
                form.validate();
            }
        };
        mailUpdateSubmitForm = function(formId, type) {
            var url = "mail/update";
            var form = dijit.byId(formId);
            if (form.isValid()) {
                var formData = form.getValues();
                var mailstatustemp = "1";
                var fileIds = dom.byId("uploadFilesU").value;
                lang.mixin(formData, {
                    senderid : userid,
                    sender : username,
                    userid : userid,
                    mailstatus : mailstatustemp,
                    filenames : fileIds
                });
                var json = JSON.stringify(formData);
                syncDB(url, json);
                form.hide();
                topic.publish("mail/insertOrUpdate", formId);
            } else {
                form.validate();
            }
        };
        mailDelete = function() {
            var ids = jQuery("#mailGird").jqGrid('getGridParam', 'selarrrow') || [];
            deletItemsCount = ids.length;
            if (deletItemsCount > 0) {
                if (confirm('确认删除所选定的项？')) {
                    var mail = {};
                    mail.id = '';
                    mail.userid = userid;
                    mail.foldertype = foldertype;
                    array.forEach(ids, function(entry, i) {
                        mail.id += entry + ",";
                    });
                    syncDB("mail/delete", JSON.stringify(mail));
                }
            } else {
                alert('请选择至少一条数据!');
            }
        };
        mailQuery = function(formId) {
            var mail = dijit.byId(formId).getValues();
            jQuery("#mailGird").jqGrid('setGridParam', {
                postData : mail,
                mtype : "post"
            }).trigger('reloadGrid');
        };
        mailfolderSubmitForm = function(formId, type) {
            var url = "mailfolder/insert";
            if (type == 'u') {
                url = "mailfolder/update";
            }
            var form = dijit.byId(formId);
            if (form.isValid()) {
                var json = JSON.stringify(form.getValues());
                syncDB(url, json);
                form.hide();
                topic.publish("mailfolder/insertOrUpdate", formId);
            } else {
                form.validate();
            }
        };
        mailfolderDelete = function() {
            var ids = jQuery("#mailfolderGird").jqGrid('getGridParam', 'selarrrow') || [];
            deletItemsCount = ids.length;
            if (ids.length > 0) {
                if (confirm('确认删除所选定的项？')) {
                    var mailfolder = {};
                    mailfolder.id = '';
                    array.forEach(ids, function(entry, i) {
                        mailfolder.id += entry + ",";
                    });
                    syncDB("mailfolder/delete", JSON.stringify(mailfolder));
                }
            } else {
                alert('请选择至少一条数据!');
            }
        };
        newMailWin = function() {
            var myDialog = new Dialog({
                title : "新建邮件",
                href : "mail/newmail",
                style : "width:600px;"
            });
            myDialog.show();
        };
        // zTree 
        var beforeDrag = function(treeId, treeNodes) {
            return false;
        };
        var zTreeOnClick = function(event, treeId, treeNode) {
            //var phonebook = jQuery("#mailfolderGird").jqGrid('getRowData', treeNode.folderid);
            foldertype = treeNode.foldertype;
            jQuery("#mailGird").jqGrid('setGridParam', {
                postData : {
                    foldertype : foldertype,
                    userid : userid
                },
                mtype : "post"
            }).trigger('reloadGrid');
        };
        var setting = {
            async : {
                enable : true,
                url : "mailfolder/queryFolderLevel"
            },
            check : {
                enable : false,
                chkboxType : {
                    "Y" : "s",
                    "N" : "p"
                }
            },
            view : {
                selectedMulti : false
            },
            edit : {
                enable : false,
                editNameSelectAll : false
            },
            data : {
                key : {
                    name : 'foldername'
                },
                simpleData : {
                    enable : false,
                    idKey : 'folderid'
                }
            },
            callback : {
                beforeDrag : beforeDrag,
                onClick : zTreeOnClick
            }
        };
        jQuery.fn.zTree.init(jQuery("#mailFolderTree"), setting);
        
        showDetails = function(id) {
            var mail = jQuery("#mailGird").jqGrid('getRowData', id);
            request.post("mail/queryMailAttach?mailid=" + mail.mailid, {
                data : "",
                headers : {
                    'Content-Type' : "application/json; charset=utf-8"
                },
                timeout : 30000
            }).then(
                    function(response) {
                        var attaches = JSON.parse(response);
                        var mailAttachSpan = dom.byId("mailAttachFiles");
                        array.forEach(attaches, function(entry, i) {
                            mailAttachSpan.innerHTML += "<a href='attachment/download?fileid=" + entry.fileid
                                    + "' style='text-decoration: none;'>" + entry.filename + "</a>&nbsp;&nbsp;";
                        });
                        dijit.byId('mailUFD').setValues(mail);
                        dijit.byId('mailUFD').show();
                    }, function(error) {
                        alert(error);
                    });
        };
        updateDetails = function(id) {
            var mail = jQuery("#mailGird").jqGrid('getRowData', id);
            dijit.byId('mailUpdate').setValues(mail);
            dijit.byId('mailUpdate').show();
        };
    });
</script>
<div>
  <div style="width: 18%; height: 555px; float: left;" data-dojo-type="dijit/layout/AccordionContainer">
    <div data-dojo-type="dijit/layout/ContentPane" data-dojo-props="selected:true,title:'邮箱目录'">
      <div>
        <button id="mailfolderReceiveBtn" data-dojo-type="dijit/form/Button" type="button" label="收邮件" onclick="mailRefresh();"></button>
        <button id="mailfolderNewBtn" data-dojo-type="dijit/form/Button" type="submit" label="发邮件">
          <script type="dojo/method" event="onClick" args="evt">
            dijit.byId('mailIFD').show();
         </script>
        </button>
      </div>
      <div>
        <ul id="mailFolderTree" class="ztree" style="margin: 0px; padding: 0; border: 0 solid white; background: white; overflow-y: hidden;"></ul>
      </div>
    </div>
  </div>
  <div style="width: 80%; float: right;">
    <div data-dojo-type="dijit/Dialog" id="mailIFD" title="新增">
      <div class="dijitDialogPaneContentArea">
        <table>
          <tr>
            <td><label for="subject">邮件标题: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, trim:true" type="text" name="subject"></td>
          </tr>
          <tr>
            <td><label for="recipientnames">收件人: </label></td>
            <td><input id="recipientSel" name="recipientnames" data-dojo-type="dijit/form/TextBox" data-dojo-props="readonly : true" style="width: 180px; border: solid 1px #85B5D9;" cType="s"
              onclick="showUserTree(this,'recipientId');" /> <input id="recipientId" data-dojo-type="dijit/form/TextBox" type="text" name="recipientids" style="display: none;"></td>
          </tr>
          <tr>
            <td><label for="fileids">附件: </label></td>
            <td><input id="uploadFilesI" data-dojo-type="dijit/form/TextBox" data-dojo-props="readonly : true" onclick="uploadComponet(this,'fileIdI');" /> <input id="fileIdI"
              data-dojo-type="dijit/form/TextBox" name="fileids" style="display: none;"></td>
          </tr>
          <tr>
            <td><label for="content">邮件内容: </label></td>
            <td><div data-dojo-type="dijit/Editor" name="content" id="MailNewContent"></div></td>
          </tr>
        </table>
      </div>
      <div class="dijitDialogPaneActionBar">
        <button data-dojo-type="dijit/form/Button" type="button" onclick="mailSaveSubmitForm('mailIFD','i')">保存</button>
        <button data-dojo-type="dijit/form/Button" type="button" onclick="mailSubmitForm('mailIFD','i')">发送</button>
        <button data-dojo-type="dijit/form/Button" type="button" onclick="mailRestForm('mailIFD');">重置</button>
      </div>
    </div>
    <div data-dojo-type="dijit/Dialog" id="mailUFD" title="查看">
      <div class="dijitDialogPaneContentArea">
        <input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="readOnly: true" type="text" name="mailid" style="display: none;">
        <table>
          <tr>
            <td><label for="subject">邮件标题: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="trim:true" type="text" name="subject" readonly="readonly"></td>
          </tr>
          <tr>
            <td><label for="sendtime">发送时间: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" type="text" name="sendtime" readonly="readonly"></td>
          </tr>
          <tr>
            <td><label for="sender">发件人: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" type="text" name="sender" readonly="readonly"></td>
          </tr>
          <tr>
            <td><label for="recipientnames">收件人: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" type="text" name="recipientnames" readonly="readonly"></td>
          </tr>
          <tr>
            <td><label for="filenames">附件: </label></td>
            <td><span id="mailAttachFiles"></span></td>
          </tr>
          <tr>
            <td><label for="content">邮件内容: </label></td>
            <td><div data-dojo-type="dijit/Editor" name="content" readonly="readonly"></div></td>
          </tr>
        </table>
      </div>
    </div>
    <div data-dojo-type="dijit/Dialog" id="mailUpdate" title="修改">
      <div class="dijitDialogPaneContentArea">
        <input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, readOnly: true" type="text" name="mailid" style="display: none;">
        <table>
          <tr>
            <td><label for="subject">邮件标题: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, trim:true" type="text" name="subject"></td>
          </tr>
          <tr>
            <td><label for="recipientnames">收件人: </label></td>
            <td><input  data-dojo-type="dijit/form/TextBox"name="recipientnames" data-dojo-props="readonly : true" style="width: 180px; border: solid 1px #85B5D9;" cType="s"
              onclick="showUserTree(this,'recipientIdU');" /> <input id="recipientIdU" data-dojo-type="dijit/form/TextBox" name="recipientids"  type="text" style="display: none;"></td>
          </tr>
          <tr>
            <td><label for="filenames">附件: </label></td>
            <td><input id="uploadFilesU" data-dojo-type="dijit/form/TextBox" data-dojo-props="readonly : true" name="filenames" onclick="uploadComponet(this,'fileIdU');" /> <input id="fileIdU"
              data-dojo-type="dijit/form/TextBox" name="fileids" style="display: none;"></td>
          </tr>
          <tr>
            <td><label for="content">邮件内容: </label></td>
            <td><div data-dojo-type="dijit/Editor" name="content" id="MailUpdateContent"></div></td>
          </tr>
        </table>
      </div>
      <div class="dijitDialogPaneActionBar">
        <button data-dojo-type="dijit/form/Button" type="button" onclick="mailUpdateSubmitForm('mailUpdate','i')">发送</button>
        <button data-dojo-type="dijit/form/Button" type="button" onclick="mailRestForm('mailUpdate');">重置</button>
      </div>
    </div>
    <fieldset>
      <legend>&nbsp;&nbsp;信息选项&nbsp;&nbsp;</legend>
      <form id="queryMailForm" data-dojo-type="dijit/form/Form" method="post">
        <div style="margin-left: 5px;">
          <table>
            <tr>
              <td><label for="sender">发件人: </label></td>
              <td width="200"><input data-dojo-type="dijit/form/TextBox" data-dojo-props="trim: true" type="text" name="sender"></td>
              <td><label for="subject">邮件标题: </label></td>
              <td width="200"><input data-dojo-type="dijit/form/TextBox" data-dojo-props="trim: true" type="text" name="subject"></td>
              <td><label for="recipientnames">收件人: </label></td>
              <td width="200"><input data-dojo-type="dijit/form/TextBox" data-dojo-props="trim: true" type="text" name="recipientnames"></td>
            </tr>
          </table>
        </div>
      </form>
      <div style="padding: 5px;">
        <button id="mailDeleteBtn" data-dojo-type="dijit/form/Button" type="button" label="删除" onclick="mailDelete();"></button>
        <button id="mailQueryBtn" data-dojo-type="dijit/form/Button" type="button" label="查询" onclick="mailQuery('queryMailForm');"></button>
      </div>
    </fieldset>
    <div id="gird">
      <table id="mailGird"></table>
      <div id="mailToolbar"></div>
    </div>

  </div>
</div>


<script type="text/javascript">
    jQuery("#mailGird").jqGrid(
            {
                url : 'mail/queryAsList',
                datatype : "json",
                autowidth : true,
                rownumbers : true,
                height : 'auto',
                colNames : [ '邮件ID', '发送人', '发送人ID', '优先级', '发送时间', '邮件内容', '邮件标题', '抄送人姓名列表', '抄送人ID列表', '收件人',
                        '收件人ID', '邮件状态1正式邮件0草稿邮件', '附件Id', '附件名称', '查看' ],
                colModel : [ {
                    name : 'mailid',
                    index : 'mailid',
                    width : 60,
                    key : true,
                    hidden : true,
                    align : 'center'
                }, {
                    name : 'sender',
                    index : 'sender',
                    align : 'center',
                    width : 80
                }, {
                    name : 'senderid',
                    index : 'senderid',
                    hidden : true
                }, {
                    name : 'importantflag',
                    index : 'importantflag',
                    width : 60,
                    align : 'center'
                }, {
                    name : 'sendtime',
                    index : 'sendtime',
                    align : 'center',
                    width : 140
                }, {
                    name : 'content',
                    index : 'content',
                    hidden : true
                }, {
                    name : 'subject',
                    index : 'subject',
                    width : 200
                }, {
                    name : 'copytonames',
                    index : 'copytonames',
                    hidden : true
                }, {
                    name : 'copytoids',
                    index : 'copytoids',
                    hidden : true
                }, {
                    name : 'recipientnames',
                    index : 'recipientnames',
                    align : 'center',
                    width : 80
                }, {
                    name : 'recipientids',
                    index : 'recipientids',
                    hidden : true
                }, {
                    name : 'mailstatus',
                    index : 'mailstatus',
                    hidden : true
                }, {
                    name : 'fileids',
                    index : 'fileids',
                    hidden : true
                }, {
                    name : 'filenames',
                    index : 'filenames',
                    hidden : true
                }, {
                    name : 'manager',
                    index : 'manager',
                    align : 'center',
                    width : 80
                } ],
                rowNum : 15,
                rowList : [ 15, 20, 25, 30 ],
                pager : '#mailToolbar',
                recordpos : 'right',
                viewrecords : true,
                sortorder : "desc",
                jsonReader : {
                    repeatitems : false
                },
                gridComplete : function() {
                    var ids = jQuery("#mailGird").jqGrid('getDataIDs');
                    for ( var i = 0; i < ids.length; i++) {
                        var cl = ids[i];
                        var mail = jQuery("#mailGird").jqGrid('getRowData', cl);
                        var currentStatus = mail['importantflag'] || '1';
                        var currentmailStatus = mail['mailstatus'] || '1';
                        var status = currentStatus == '2' ? '重要' : (currentStatus == '3' ? '非常重要' : '一般');
                        var manager = "";
                        if (currentmailStatus == '0') {
                            manager = "<a style='width:400px;' href='javascript:void(0);' onclick=\"updateDetails('"
                                    + cl + "');\">修改</a>";
                        } else {
                            manager = "<a style='width:40px;' href='javascript:void(0);' onclick=\"showDetails('" + cl
                                    + "');\">查看</a>";
                        }
                        
                        jQuery("#mailGird").jqGrid('setRowData', cl, {
                            importantflag : status,
                            manager : manager
                        });
                    }
                },
                multiselect : true,
                shrinkToFit : false,
                caption : "邮件列表"
            });
    jQuery("#mailGird").jqGrid('navGrid', '#mailToolbar', {
        edit : false,
        add : false,
        del : false,
        search : false,
        refresh : true
    });
</script>